package org.example.ThreadPool;

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class CompletionServiceSty {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建一个线程池, 用于执行异步计算任务, 这里的线程池大小为4-10个, 队列容量为20, 超出容量则使用AbortPolicy策略。
        ExecutorService executorService = new ThreadPoolExecutor(4, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(20), new ThreadPoolExecutor.AbortPolicy());
        // 创建一个CompletionService, 它封装了一个ExecutorService。
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
        // 提交10个异步计算任务到CompletionService。
        IntStream.range(0, 10).forEach(i -> {
            completionService.submit(() -> {
                Thread.sleep((long) (Math.random() * 1000));
                System.out.println(Thread.currentThread().getName()+"计算结果："+i*i);
                return i * i;
            });
        });

        for (int i = 0; i < 10; ++i) {
            int result = completionService.take().get();
            System.out.println(result);
        }

        executorService.shutdown();
    }
}
